package com.lpdemilis.pokermanager;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class SearchGroupActivity extends Activity implements MyAsyncListener {
	private User user;
	private int groupindex;
	private int groupid;
	protected String SERVER_URL;
	protected CustomHttpClient client;
	protected String[] groupids;
	protected String[] fullnames;
	// protected String[] shortnames;
	protected String[] usersFullnames;
	protected String[] passwords;
	protected String[] roleids;
	protected String[] needauths;

	protected TextView returnTextView;
	protected EditText groupEditText;
	protected Button searchGroupButton;
	protected TextView groupResultsTextView;
	protected LinearLayout groupResultsLinearLayout;
	protected ArrayList<LinearLayout> groupsLinesArrayList;
	protected int previous;

	protected LinearLayout enrolMeLinearLayout;
	protected EditText passwordEditText;
	protected Button enrolMeButton;
	protected TextView orTextView;
	protected LinearLayout askEnrolmentLinearLayout;
	protected Button askEnrolmentButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_searchgroup);

		if (Build.MANUFACTURER.equals("unknown")) {
			SERVER_URL = this.getString(R.string.URL_local);
		} else {
			SERVER_URL = this.getString(R.string.URL);
		}
		
		TextView activityTitleTextView = (TextView) findViewById(R.id.activityTitleTextView);
		Typeface titleTypeface = Typeface.createFromAsset(getAssets(),
                "fonts/POKERPN.TTF");        
        activityTitleTextView.setTypeface(titleTypeface);

		user = (User) getIntent().getSerializableExtra("user");
		groupindex = getIntent().getIntExtra("groupindex", 0);
		previous = -1;
		groupid = 0;

		// interface
		returnTextView = (TextView) findViewById(R.id.returnTextView);
		groupEditText = (EditText) findViewById(R.id.groupEditText);
		searchGroupButton = (Button) findViewById(R.id.searchGroupButton);
		groupResultsTextView = (TextView) findViewById(R.id.groupResultsTextView);
		groupResultsLinearLayout = (LinearLayout) findViewById(R.id.groupResultsLinearLayout);

		// listener
		searchGroupButton.setOnClickListener(searchGroupButtonClickListener);
	}

	public enum ActionsEnum {
		getGroup, enrolUser, error;
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(SearchGroupActivity.this, MainActivity.class);
		intent.putExtra("groupindex", groupindex);
		intent.putExtra("user", user);
		if (groupid > 0) {
			intent.putExtra("groupid", groupid);
		}
		SearchGroupActivity.this.startActivity(intent);
		SearchGroupActivity.this.finish();
	}

	View.OnClickListener searchGroupButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (groupEditText.getText().toString().trim().equals("")) {
				returnTextView.setText(R.string.empty_group);
				groupEditText.requestFocus();
				return;
			} else {
				returnTextView.setText("");
				getGroup();
			}
		}
	};

	public void getGroup() {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.getGroup.toString();
			String paramName1 = "group";
			String paramValue1 = groupEditText.getText().toString();
			String paramName2 = "userid";
			String paramValue2 = String.valueOf(user.getId());
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case getGroup:
			getGroupReturn(returnArray);
			break;
		case enrolUser:
			enrolUserReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void getGroupReturn(String[] returnArray) {
		groupsLinesArrayList = new ArrayList<LinearLayout>();
		groupResultsLinearLayout.removeAllViewsInLayout();
		groupResultsTextView.setVisibility(View.VISIBLE);

		if (returnArray.length <= 1) {
			TextView groupName = new TextView(this);
			groupName.setText(this.getString(R.string.no_group_found));
			groupName.setTextAppearance(this, R.style.custom_textview);
			groupName.setPadding(Utils.convertToPixel(10, this),
					Utils.convertToPixel(10, this),
					Utils.convertToPixel(10, this),
					Utils.convertToPixel(10, this));
			groupResultsLinearLayout.addView(groupName);
		} else {
			groupids = returnArray[2].split("@@");
			fullnames = returnArray[4].split("@@");
			// shortnames = returnArray[6].split("@@");
			usersFullnames = returnArray[8].split("@@");
			passwords = returnArray[10].split("@@");
			roleids = returnArray[12].split("@@");
			needauths = returnArray[14].split("@@");

			if (groupids[0].trim().equals("")) {
				TextView groupName = new TextView(this);
				groupName.setText(this.getString(R.string.no_group_found));
				groupName.setTextAppearance(this, R.style.custom_textview);
				groupName.setPadding(Utils.convertToPixel(10, this),
						Utils.convertToPixel(10, this),
						Utils.convertToPixel(10, this),
						Utils.convertToPixel(10, this));
				groupResultsLinearLayout.addView(groupName);
			} else {
				for (int i = 0; i < fullnames.length; i++) {
					groupsLinesArrayList.add(i, new LinearLayout(this));
					groupsLinesArrayList.get(i).setOrientation(
							LinearLayout.VERTICAL);
					groupsLinesArrayList.get(i).setId(i);

					if (roleids[i].trim().equals("0")) {
						groupsLinesArrayList.get(i).setOnClickListener(
								groupsLinesClickListener);
					}

					if (i % 2 == 0) {
						groupsLinesArrayList.get(i).setBackgroundResource(
								R.drawable.faixa);
					} else {
						groupsLinesArrayList.get(i).setBackgroundResource(
								R.drawable.faixa1);
					}

					LinearLayout groupNameLinearLayout = new LinearLayout(this);
					groupNameLinearLayout
							.setOrientation(LinearLayout.HORIZONTAL);
					groupNameLinearLayout.setGravity(Gravity.CENTER_VERTICAL);

					TextView groupNameTextView = new TextView(this);
					groupNameTextView.setText(fullnames[i]);
					groupNameTextView.setTextAppearance(this,
							R.style.custom_textview);
					groupNameTextView.setPadding(
							Utils.convertToPixel(10, this),
							Utils.convertToPixel(10, this),
							Utils.convertToPixel(10, this),
							Utils.convertToPixel(10, this));

					groupNameTextView
							.setLayoutParams(new LinearLayout.LayoutParams(
									LayoutParams.MATCH_PARENT,
									LayoutParams.WRAP_CONTENT, (float) 1));
					groupNameLinearLayout.addView(groupNameTextView);

					ImageView groupImageView = new ImageView(this);
					groupImageView.setBackgroundResource(R.drawable.lock);
					groupImageView.setLayoutParams(new LayoutParams(Utils
							.convertToPixel(32, this), Utils.convertToPixel(40,
							this)));

					if ((passwords[i].trim().equals(""))
							|| (passwords[i].trim().equals("NULL"))) {
						groupImageView.setVisibility(View.INVISIBLE);
					}

					groupNameLinearLayout.addView(groupImageView);

					View spacer = new View(this);
					spacer.setLayoutParams(new LayoutParams(Utils
							.convertToPixel(10, this),
							LayoutParams.MATCH_PARENT));
					groupNameLinearLayout.addView(spacer);

					groupsLinesArrayList.get(i).addView(groupNameLinearLayout);

					TextView usersFullnamesTextView = new TextView(this);
					StringBuilder sb = new StringBuilder();

					String[] groupUsersFullnames = usersFullnames[i]
							.split(";;");

					if (!groupUsersFullnames[0].trim().equals("")) {
						for (int k = 0; k < groupUsersFullnames.length - 1; k++) {
							if (k > 0) {
								sb.append("\n");
							}
							sb.append(this.getString(R.string.moderator));
							sb.append(" ");
							sb.append(groupUsersFullnames[k]);
						}

						usersFullnamesTextView.setText(sb.toString());
						usersFullnamesTextView.setTextColor(Color.WHITE);
						usersFullnamesTextView.setPadding(
								Utils.convertToPixel(10, this),
								Utils.convertToPixel(0, this),
								Utils.convertToPixel(10, this),
								Utils.convertToPixel(10, this));

						groupsLinesArrayList.get(i).addView(
								usersFullnamesTextView);
					}

					if (!roleids[i].trim().equals("0")) {
						TextView memberTextView = new TextView(this);
						if (needauths[i].trim().equals("1")) {
							memberTextView.setText(this
									.getString(R.string.waiting_auth));
						} else {
							memberTextView.setText(this
									.getString(R.string.already_member));
						}

						memberTextView.setTextColor(getResources().getColor(
								R.color.title_color));
						memberTextView.setPadding(
								Utils.convertToPixel(10, this),
								Utils.convertToPixel(10, this),
								Utils.convertToPixel(10, this),
								Utils.convertToPixel(10, this));
						memberTextView.setGravity(Gravity.CENTER_HORIZONTAL);
						groupsLinesArrayList.get(i).addView(memberTextView);

						View spacer1 = new View(this);
						spacer1.setLayoutParams(new LayoutParams(
								LayoutParams.WRAP_CONTENT, Utils
										.convertToPixel(10, this)));
						groupsLinesArrayList.get(i).addView(spacer1);
					}

					groupResultsLinearLayout.addView(groupsLinesArrayList
							.get(i));
				}
			}
		}
	}

	private void errorReturn(String[] returnArray) {

	}

	private void enrolUserReturn(final String[] returnArray) {
		AlertDialog alertDialog = new AlertDialog.Builder(
				SearchGroupActivity.this).create();
		if (returnArray[2].equals("1")) {
			alertDialog.setTitle(R.string.ask_enrolment);
		} else {
			alertDialog.setTitle(R.string.enrol_me);
		}

		if (returnArray.length <= 3) {
			if (returnArray[2].equals("1")) {
				alertDialog.setMessage(SearchGroupActivity.this
						.getString(R.string.ask_enrolment_error));
			} else {
				alertDialog.setMessage(SearchGroupActivity.this
						.getString(R.string.enrol_me_error));
			}
		} else {
			if (returnArray[2].equals("1")) {
				alertDialog.setMessage(SearchGroupActivity.this
						.getString(R.string.ask_enrolment_ok));
			} else {
				alertDialog.setMessage(SearchGroupActivity.this
						.getString(R.string.enrol_me_ok));
			}
		}

		alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
				SearchGroupActivity.this.getString(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (returnArray.length > 3) {
							groupid = Integer.parseInt(returnArray[4]);
							onBackPressed();
						}
					}
				});

		alertDialog.show();
	}

	View.OnClickListener groupsLinesClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (previous >= 0) {
				groupsLinesArrayList.get(previous).removeView(
						enrolMeLinearLayout);
				groupsLinesArrayList.get(previous).removeView(orTextView);
				groupsLinesArrayList.get(previous).removeView(
						askEnrolmentLinearLayout);
			}

			if (previous == v.getId()) {
				previous = -1;
				return;
			}

			previous = v.getId();

			if (!passwords[v.getId()].trim().equals("")) {
				enrolMeLinearLayout = new LinearLayout(SearchGroupActivity.this);
				enrolMeLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
				enrolMeLinearLayout.setPadding(
						Utils.convertToPixel(10, SearchGroupActivity.this),
						Utils.convertToPixel(10, SearchGroupActivity.this),
						Utils.convertToPixel(10, SearchGroupActivity.this),
						Utils.convertToPixel(10, SearchGroupActivity.this));
				enrolMeLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
				passwordEditText = new EditText(SearchGroupActivity.this);
				passwordEditText
						.setBackgroundResource(R.drawable.custom_edittext_style);
				passwordEditText.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
						(float) 1));
				passwordEditText
						.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
				View spacer = new View(SearchGroupActivity.this);
				spacer.setLayoutParams(new LayoutParams(Utils.convertToPixel(
						10, SearchGroupActivity.this), Utils.convertToPixel(40,
						SearchGroupActivity.this)));
				enrolMeButton = Utils.setButtonStyle_sorbus(
						SearchGroupActivity.this, new Button(
								SearchGroupActivity.this));
				enrolMeButton.setText(R.string.enrol_me);
				enrolMeButton.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, Utils.convertToPixel(40,
								SearchGroupActivity.this), (float) 2));
				enrolMeButton.setOnClickListener(enrolMeButtonClickListener);
				enrolMeLinearLayout.addView(passwordEditText);
				enrolMeLinearLayout.addView(spacer);
				enrolMeLinearLayout.addView(enrolMeButton);

				groupsLinesArrayList.get(v.getId())
						.addView(enrolMeLinearLayout);

				orTextView = new TextView(SearchGroupActivity.this);
				orTextView.setText(SearchGroupActivity.this
						.getString(R.string.or));
				orTextView.setTextAppearance(SearchGroupActivity.this,
						R.style.custom_textview);
				orTextView.setPadding(
						Utils.convertToPixel(5, SearchGroupActivity.this),
						Utils.convertToPixel(5, SearchGroupActivity.this),
						Utils.convertToPixel(5, SearchGroupActivity.this),
						Utils.convertToPixel(5, SearchGroupActivity.this));
				orTextView.setGravity(Gravity.CENTER_HORIZONTAL);

				groupsLinesArrayList.get(v.getId()).addView(orTextView);
			}

			askEnrolmentLinearLayout = new LinearLayout(
					SearchGroupActivity.this);
			askEnrolmentLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
			askEnrolmentLinearLayout.setPadding(
					Utils.convertToPixel(10, SearchGroupActivity.this),
					Utils.convertToPixel(10, SearchGroupActivity.this),
					Utils.convertToPixel(10, SearchGroupActivity.this),
					Utils.convertToPixel(10, SearchGroupActivity.this));
			askEnrolmentLinearLayout.setGravity(Gravity.CENTER_VERTICAL);

			askEnrolmentButton = Utils.setButtonStyle_sorbus(
					SearchGroupActivity.this, new Button(
							SearchGroupActivity.this));
			askEnrolmentButton.setText(R.string.ask_enrolment);
			askEnrolmentButton.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, Utils.convertToPixel(40,
							SearchGroupActivity.this)));
			askEnrolmentButton
					.setOnClickListener(askEnrolmentButtonClickListener);

			askEnrolmentLinearLayout.addView(askEnrolmentButton);

			groupsLinesArrayList.get(v.getId()).addView(
					askEnrolmentLinearLayout);

			View spacer = new View(SearchGroupActivity.this);
			spacer.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
					Utils.convertToPixel(5, SearchGroupActivity.this)));
			groupsLinesArrayList.get(v.getId()).addView(spacer);
		}
	};

	View.OnClickListener enrolMeButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					SearchGroupActivity.this).create();
			alertDialog.setTitle(R.string.enrol_me);
			alertDialog.setMessage(SearchGroupActivity.this
					.getString(R.string.enrol_me_confirm));
			alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
					SearchGroupActivity.this.getString(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							enrolMe();
						}
					});
			alertDialog
					.setButton(DialogInterface.BUTTON_NEGATIVE,
							SearchGroupActivity.this
									.getString(android.R.string.cancel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									return;
								}
							});

			alertDialog.show();
		}
	};

	View.OnClickListener askEnrolmentButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					SearchGroupActivity.this).create();
			alertDialog.setTitle(R.string.ask_enrolment);
			alertDialog.setMessage(SearchGroupActivity.this
					.getString(R.string.ask_enrolment_confirm));
			alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
					SearchGroupActivity.this.getString(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							askEnrolment();
						}
					});
			alertDialog
					.setButton(DialogInterface.BUTTON_NEGATIVE,
							SearchGroupActivity.this
									.getString(android.R.string.cancel),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									return;
								}
							});

			alertDialog.show();
		}
	};

	private void enrolMe() {
		if (passwordEditText.getText().toString().trim()
				.equals(passwords[previous].trim())) {
			try {
				client = new CustomHttpClient(this,
						this.getString(R.string.wait_message), true);
				String action = ActionsEnum.enrolUser.toString();
				String paramName1 = "userid";
				String paramValue1 = String.valueOf(user.getId());
				String paramName2 = "groupid";
				String paramValue2 = groupids[previous].toString();
				String paramName3 = "needauth";
				String paramValue3 = "0";
				client.execute(SERVER_URL, action, paramName1, paramValue1,
						paramName2, paramValue2, paramName3, paramValue3);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			AlertDialog alertDialog = new AlertDialog.Builder(
					SearchGroupActivity.this).create();
			alertDialog.setTitle(R.string.enrol_me);
			alertDialog.setMessage(SearchGroupActivity.this
					.getString(R.string.password_error_group));
			alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
					SearchGroupActivity.this.getString(android.R.string.ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});

			alertDialog.show();
		}
	}

	private void askEnrolment() {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.enrolUser.toString();
			String paramName1 = "userid";
			String paramValue1 = String.valueOf(user.getId());
			String paramName2 = "groupid";
			String paramValue2 = groupids[previous].toString();
			String paramName3 = "needauth";
			String paramValue3 = "1";
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2, paramName3, paramValue3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_searchgroup, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent intent;
		switch (item.getItemId()) {
		case R.id.menu_logoff:
			intent = new Intent(SearchGroupActivity.this, LoginActivity.class);
			SearchGroupActivity.this.startActivity(intent);
			SearchGroupActivity.this.finish();
			return true;
		case R.id.menu_creategroup:
			intent = new Intent(SearchGroupActivity.this,
					CreateGroupActivity.class);
			intent.putExtra("user", user);
			intent.putExtra("groupindex", groupindex);
			intent.putExtra("groupid", groupid);
			SearchGroupActivity.this.startActivity(intent);
			SearchGroupActivity.this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
